#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>

#define INIT_FD    -1

#define FEED        5

static volatile int m_fd = INIT_FD;

void sighandler(int s)
{
	m_fd = INIT_FD;
}

void feed_dog(void)
{
	if ((m_fd = open("/dev/watchdog", O_WRONLY)) < 0)
	{
		perror("open()");
		return;
	}
	while (m_fd > INIT_FD)
	{
		sleep(FEED);
		write(m_fd, "a", 1);
	}
	write(m_fd, "V", 1);
	close(m_fd);
}

int main(void)
{
	int i = 0;
	int fd_null = -1;
	pid_t pid;

	fflush(NULL);
	pid = fork();
	if (pid < 0)
	{
		perror("fork()");
		return 1;
	}
	else if (0 == pid)
	{
		umask(0);

		if (setsid() < 0)
		{
			perror("setsid()");
		}

		if (SIG_ERR == signal(SIGTERM, sighandler))
		{
			fprintf(stderr, "WARNING: Signal handle failed!\n");
		}

		chdir("/");

		fd_null = open("/dev/null", O_RDWR);
		for (i = 0; i < 3; i++)
		{
			dup2(fd_null, i);
		}

		feed_dog();

		close(fd_null);
	}
	else
	{
		// Parent do nothing.
	}
	return 0;
}

